package org.jxy.study.rpc.config;

import io.netty.channel.Channel;
import org.jxy.study.rpc.netty.ConnectManage;
import org.jxy.study.rpc.netty.NettyClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

/**
 * @author jxy
 * @className ServiceDiscover
 * @description 服务发现
 * @date 2021/3/11 21:27
 */
@Component
public class ServiceDiscover {
    private Logger logger = LoggerFactory.getLogger(ServiceDiscover.class);
    @Resource
    private NettyClient nettyClient;
    @Resource
    private ConnectManage connectManage;
    @Value("${rpc.netty.client.address}")
    private String address;
    @Value("${rpc.netty.client.port}")
    private int port;
    @PostConstruct
    public void init() {
        this.initServiceList();
    }

    public void initServiceList() {
        logger.info("开始连接服务器");
        try {
            SocketAddress socketAddress = new InetSocketAddress(address, port);
            Channel connect = nettyClient.connect(socketAddress);
            connectManage.addChannel(socketAddress, connect);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
